package cn.bupt.adt.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.dao.autogenerate.DoctorAppUserMapper;
import cn.bupt.adt.dao.autogenerate.DoctorMapper;
import cn.bupt.adt.dao.autogenerate.Doctor_OperationTypeMapper;
import cn.bupt.adt.entity.autogenerate.Doctor;
import cn.bupt.adt.entity.autogenerate.DoctorAppUser;
import cn.bupt.adt.entity.autogenerate.DoctorAppUserExample;
import cn.bupt.adt.entity.autogenerate.DoctorExample;
import cn.bupt.adt.entity.autogenerate.Doctor_OperationType;
import cn.bupt.adt.service.IDoctorAppUserService;
import cn.bupt.adt.util.AccountUtil;
import cn.bupt.adt.util.ImageUtil;
import cn.bupt.adt.util.MD5Util;
import cn.bupt.adt.util.NetDataAccessUtil;
import cn.bupt.adt.util.RedisUtil;
import cn.bupt.adt.util.SendSMSUtil;

@Service
public class DoctorAppUserService implements IDoctorAppUserService {

	@Autowired
	DoctorMapper doctorMapper;
	@Autowired
	DoctorAppUserMapper doctorAppUserMapper;
	// @Autowired
	// DoctorViewMapper doctorViewMapper;

	@Autowired
	Doctor_OperationTypeMapper doctor_OperationTypeMapper;

	@Override
	public DoctorAppUser getDoctorByAccount(String account) {
		DoctorAppUserExample ex = new DoctorAppUserExample();
		ex.createCriteria().andAccountEqualTo(account);
		List<DoctorAppUser> docs = doctorAppUserMapper.selectByExample(ex);
		if (docs.size() == 1)
			return docs.get(0);
		else
			return null;
	}

	@Override
	public void updateLoginTimeById(Integer id, Date loginTime) {
		DoctorAppUser doc = doctorAppUserMapper.selectByPrimaryKey(id);
		if (doc != null) {
			doc.setLastLoginTime(doc.getLoginTime());
			doc.setLoginTime(loginTime);
			doctorAppUserMapper.updateByPrimaryKeySelective(doc);
		}
	}

	@Override
	public DoctorAppUser checkInviteCode(String invitaCode) {
		DoctorAppUserExample ex = new DoctorAppUserExample();
		ex.createCriteria().andInvitaCodeEqualTo(invitaCode);
		List<DoctorAppUser> docs = doctorAppUserMapper.selectByExample(ex);
		return docs.size() == 1 ? docs.get(0) : null;
	}

	@Override
	public boolean addDoctorAppUser(DoctorAppUser user) {
		int i = doctorAppUserMapper.insert(user);
		return i == 1;
	}

	@Override
	public DoctorAppUser getDoctorById(Integer userId) {
		return doctorAppUserMapper.selectByPrimaryKey(userId);
	}

	@Override
	public boolean changePasswd(DoctorAppUser doc, String newPasswd) {
		doc.setPasswd(MD5Util.MD5(newPasswd));
		int i = doctorAppUserMapper.updateByPrimaryKeySelective(doc);
		return i == 1;
	}

	@Override
	public void updateDoctorAppuser(DoctorAppUser doc) {
		doctorAppUserMapper.updateByPrimaryKeySelective(doc);
	}

	/*
	 * @Override public DoctorView getDoctorViewById(Integer userId) {
	 * DoctorViewExample example = new DoctorViewExample();
	 * example.createCriteria().andAppIdEqualTo(userId); List<DoctorView> list =
	 * doctorViewMapper.selectByExample(example); return list.size() ==
	 * 1?list.get(0):null; }
	 */
	@Override
	public boolean addDoctorAppUser(DoctorAppUser doc, int[] operationTypesId, HttpServletRequest request) {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		// rootPath = 项目所在目录+分隔符+upload+分隔符
		String rootPath = req.getSession().getServletContext().getRealPath("") + "/../" + Constants.IMAGE_PATH;
		// List<MultipartFile> idCards = req.getFiles("idCards");
		Long time = System.currentTimeMillis();
		String timePath = time.toString() + "/";
		MultipartFile portrait = req.getFile("portr");
		MultipartFile deg = req.getFile("deg");
		MultipartFile gra = req.getFile("gra");
		MultipartFile pro = req.getFile("pro");
		MultipartFile cert = req.getFile("cert");
		MultipartFile qua = req.getFile("qua");
		MultipartFile idPos = req.getFile("idPos");
		MultipartFile idNeg = req.getFile("idNeg");
		List<String> path = new ArrayList<>();
		try {
			if (portrait != null && portrait.getSize() != 0) {
				path.add(ImageUtil.uploadImage(portrait, Constants.DOC_PORTRAIT + timePath, rootPath, 1));
				doc.setPortrait(path.get(0));
				path.clear();
			}
			if (deg != null && deg.getSize() != 0) {
				path.add(ImageUtil.uploadImage(deg, Constants.DEG_PATH + timePath, rootPath, 1));
				doc.setDegreeImg(path.get(0));
				path.clear();
			}
			if (gra != null && gra.getSize() != 0) {
				path.add(ImageUtil.uploadImage(gra, Constants.GRA_PATH + timePath, rootPath, 1));
				doc.setGraduationImg(path.get(0));
				path.clear();
			}
			if (qua != null && qua.getSize() != 0) {
				path.add(ImageUtil.uploadImage(qua, Constants.QUA_PATH + timePath, rootPath, 1));
				doc.setQualificationImg(path.get(0));
				path.clear();
			}
			if (cert != null && cert.getSize() != 0) {
				path.add(ImageUtil.uploadImage(cert, Constants.CERT_PATH + timePath, rootPath, 1));
				doc.setCertificationImg(path.get(0));
				path.clear();
			}
			if (pro != null && pro.getSize() != 0) {
				path.add(ImageUtil.uploadImage(pro, Constants.PRO_PATH + timePath, rootPath, 1));
				doc.setProfessionalTitleImg(path.get(0));
				path.clear();
			}
			if (idPos != null && idPos.getSize() != 0) {
				path.add(ImageUtil.uploadImage(idPos, Constants.IDEN_POS_PATH + timePath, rootPath, 1));
				doc.setIdentificationPosImg(path.get(0));
				path.clear();
			}
			if (idNeg != null && idNeg.getSize() != 0) {
				path.add(ImageUtil.uploadImage(idNeg, Constants.IDEN_NEG_PATH + timePath, rootPath, 1));
				doc.setIdentificationNegImg(path.get(0));
				path.clear();
			}
		} catch (Exception e) {

		}
		int i = doctorAppUserMapper.updateByPrimaryKeySelective(doc);
		for (int x : operationTypesId) {
			Doctor_OperationType dot = new Doctor_OperationType();
			dot.setDoctorId(doc.getId());
			dot.setOperationTypeId(x);
			doctor_OperationTypeMapper.insert(dot);
		}
		return i == 1;
	}

	@Override
	public void sendSmsForResetPasswd(String phone, NetDataAccessUtil nau) {
		DoctorAppUserExample ex = new DoctorAppUserExample();
		ex.createCriteria().andPhoneEqualTo(phone);
		List<DoctorAppUser> doctors = doctorAppUserMapper.selectByExample(ex);
		if (doctors.size() == 0) {
			nau.setResultDesp("不存在该手机号对应的用户，请检查您的输入");
			nau.setResult(0);
			return;
		} else if (doctors.size() == 1) {
			SendSMSUtil sms = new SendSMSUtil();
			String validCode = AccountUtil.getRandomInvitaCode(6);
			RedisUtil.set(validCode, doctors.get(0).getId());
			RedisUtil.expire(validCode, 60);
			sms.SendSMS(phone, new String[] { validCode }, Constants.SMS_DOC_RESET_PASSWD);
			nau.setResult(1);
			nau.setResultDesp("验证码即将发送到该手机号上，请在60秒内输入验证码");
			return;
		} else {
			nau.setResultDesp("未知错误");
			nau.setResult(2);
		}
	}

}
